package kcms.ppt.action;


import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import kcms.db.CourseJiaoke;
import kcms.db.PptAndContent;
import kcms.db.PptTeaContent;
import kcms.db.Pptcontent;
import kcms.db.User;
import kcms.ppt.service.PptService;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

@Controller("PptAction")
@Scope("prototype")
public class PptAction extends ActionSupport{
	private static final long serialVersionUID = 1L;
	@Resource
	private PptService pptservice;
	private String[] chapter,description;
	private File[] doc;   
    private String[] docFileName;   
    private String[] docContentType;
    private String[] cid,csn;
    private String search;
    private String[] checkbox;
    private String[] delcheck;
    private int currentpage,pagesize;
    private String startdate,enddate;
    private List<CourseJiaoke> coursejiaoke;
    private List<PptAndContent> pac;
    private List<PptTeaContent> ptc;
    private String pptid;
    private InputStream inputStream;
    private String fileName;
    private String[] downloadcheck;
	private String[] downLoadPaths;
	private String[] downLoadNames;
	private static String localpath="D:/kcms/uploadedpptfile";
	
	private OutputStream res;
	private ZipOutputStream zos;
	private String outPath;
	
	
    //upload method
	public String upload() throws Exception{
			ServletActionContext.getRequest().setCharacterEncoding("UTF-8");
			//String realpath = ServletActionContext.getServletContext().getRealPath("/uploadedpptfile");
			String realpath = localpath;
	        System.out.println(realpath);
	        Pptcontent delp;
	        if (doc != null) {
	        	int pptid;
	            File savedir=new File(realpath);
	            if(!savedir.getParentFile().exists())
	                savedir.getParentFile().mkdirs();
	            for(int i=0;i<doc.length;i++){
	            	pptid=this.pptservice.queryPptId(cid[i],csn[i],chapter[i]);
	            	if(pptid!=-1){		//在ppt表中找到了对应pptid
	            		delp=pptservice.deletePptResourceByPptid(pptid);//删除对应pptcontent数据库记录
	            		File delfile= new File(savedir, delp.getResource());
	            		if(delfile.isFile()&&delfile.exists())
	            			delfile.delete();//如果文件存在，同时删除文件
	            	}
	            	else{//没找到pptid，则在ppt表中新建一行记录
	            		pptid=pptservice.createNewPptid(cid[i],csn[i],chapter[i]).getPptid();
	            	}
	            	//此时一定有一个pptid，开始存文件并保存记录到pptcontent
	            	String filename=generateFileName(docFileName[i]);
	                File savefile = new File(savedir, filename);
	                FileUtils.copyFile(doc[i], savefile);
	                pptservice.saveContentRecord(pptid,filename,docFileName[i],description[i]);//存失败为false
	            }
	            //ActionContext.getContext().put("message", "文件上传成功");
		}
	        return "success";
	}
	
	private String generateFileName(String fileName) {   
        DateFormat format = new SimpleDateFormat("yyMMddHHmmss");   
        String formatDate = format.format(new Date());     
        int random = new Random().nextInt(10000);   
        int position = fileName.lastIndexOf(".");   
        String extension = fileName.substring(position);   
        return formatDate + random + extension;   
    }

	//list All ppt and filter for students
	public String list(){
		User u=(User) ActionContext.getContext().getSession().get("user");
		coursejiaoke=pptservice.getAllCourseAttendedBy(u);
		pac=pptservice.listPpt(checkbox,search,startdate,enddate,currentpage,pagesize);
		return "listsuccess";
	}
	//for teachers
	public String tealist(){
		User u=(User) ActionContext.getContext().getSession().get("user");
		coursejiaoke=pptservice.getAllCourseAttendedBy(u);
		ptc=pptservice.listPptByTid(u.getId());
		return "tealistsuccess";
	}
	public String muldel(){
		
		for(String pid:delcheck){
		pptservice.deletePptResourceByPptid(Integer.parseInt(pid));
		pptservice.deletePptByPptid(pid);
		pptservice.deleteAllPptStatusByPptid(pid);
		}
		return "delfilesuccess";
	}
	
	public String delFile(){
		pptservice.deletePptResourceByPptid(Integer.parseInt(pptid));
		boolean t1=pptservice.deletePptByPptid(pptid);
		boolean t2=pptservice.deleteAllPptStatusByPptid(pptid);
		if(t1==true&&t2==true)
			return "delfilesuccess";
		else
			return "delfilefail";
	}
	
    // 单个下载
    public String downloadFile() {
    	try{
    	//System.out.println(getFileName());
    	Pptcontent pc=pptservice.getRealFileNameByPptid(pptid);
    	ServletActionContext.getRequest().setCharacterEncoding("UTF-8");
    	//String realpath = ServletActionContext.getServletContext().getRealPath("/uploadedpptfile");
    	String realpath = localpath;
        // 如果下载文件名为中文，进行字符编码转换
        //ServletActionContext.getResponse().setHeader("Content-Disposition","attachment;fileName="+ java.net.URLEncoder.encode(pc.getName(), "UTF-8"));
        File savedfile = new File(realpath+"/"+pc.getResource());
        inputStream = new FileInputStream(savedfile);
        fileName=new String(pc.getName().getBytes(),"ISO8859-1");
        System.out.println(fileName);
    	/*Pptcontent pc=pptservice.getRealFileNameByPptid(pptid);
    	ServletActionContext.getRequest().setCharacterEncoding("UTF-8");
        return ServletActionContext.getServletContext().getResourceAsStream("/uploadedpptfile/"+pc.getResource());*/
    	return "downsuccess";
        }catch(Exception e){
        	e.printStackTrace();
        	return "downfail";
        }
    }
    //archive download
    public String zipdownload(){
    	try{
    	this.convertAddr();
    	// 有数据可以下载
    	if (downLoadPaths.length != 0) {
    		// 进行预处理
    		this.preProcess();
    	} else {
    		// 没有文件可以下载，返回nodata
    		return "nodata";
    	}
    	// 处理
    	this.writeZip();
    	// 后处理关闭流
    	this.afterProcess();
    	return null;
    	}catch(Exception e){
    		e.printStackTrace();
    		return "nodata";
    	}
    }
	
    private void convertAddr(){
    	Pptcontent p;
    	int count=downloadcheck.length;
    	downLoadPaths=new String[count];
    	downLoadNames=new String[count];
    	for(int i=0;i<downloadcheck.length;i++){
    		p=this.pptservice.getRealFileNameByPptid(downloadcheck[i]);
    		downLoadPaths[i]=localpath+"/"+p.getResource();
    		downLoadNames[i]=p.getName();
    	}
    	/*int size=temppath.size();
    	downLoadPaths=(String[])temppath.toArray(new String[size]);*/
    }
    
 // 压缩处理
 	private void writeZip() throws Exception {
 		byte[] buf = new byte[8192];
 		int len;
 		
 		for (int i=0;i<downLoadPaths.length;i++) {
 			File file = new File(downLoadPaths[i]);
 			if (!file.isFile())
 				continue;
 			ZipEntry ze = new ZipEntry(downLoadNames[i]); //apache jar的ZipEntry
 			zos.putNextEntry(ze);
 			BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
 			while ((len = bis.read(buf)) > 0) {
 				zos.write(buf, 0, len);
 			}
 			bis.close();
 			zos.closeEntry();
 		}
 	}

 	// 预处理
 	private void preProcess() throws Exception {
 		HttpServletResponse response = ServletActionContext.getResponse();
 		res = response.getOutputStream();
 		// 清空输出流(在迅雷下载不会出现一长窜)
 		response.reset();
 		// 设定输出文件头
 		response.setHeader("Content-Disposition", "attachment;filename=ArchivedPPT_"+generateFileName("ArchivedPPT.zip"));
 		response.setContentType("application/zip");
 		zos = new ZipOutputStream(res);
 	}

 	// 后处理
 	private void afterProcess() throws Exception {

 		zos.close();
 		res.close();
 	}
    
    
	public File[] getDoc() {
		return doc;
	}

	public void setDoc(File[] doc) {
		this.doc = doc;
	}
	public String[] getDocFileName() {
		return docFileName;
	}
	public void setDocFileName(String[] docFileName) {
		this.docFileName = docFileName;
	}
	public String[] getDocContentType() {
		return docContentType;
	}
	public void setDocContentType(String[] docContentType) {
		this.docContentType = docContentType;
	}
	public static long getSerialversionuid() {
		return serialVersionUID;
	}

	public PptService getPptservice() {
		return pptservice;
	}

	public void setPptservice(PptService pptservice) {
		this.pptservice = pptservice;
	}

	public String[] getChapter() {
		return chapter;
	}

	public void setChapter(String[] chapter) {
		this.chapter = chapter;
	}

	public String[] getCid() {
		return cid;
	}

	public void setCid(String[] cid) {
		this.cid = cid;
	}

	public String[] getCsn() {
		return csn;
	}

	public void setCsn(String[] csn) {
		this.csn = csn;
	}

	public String[] getDescription() {
		return description;
	}

	public void setDescription(String[] description) {
		this.description = description;
	}

	public List<CourseJiaoke> getCoursejiaoke() {
		return coursejiaoke;
	}

	public void setCoursejiaoke(List<CourseJiaoke> coursejiaoke) {
		this.coursejiaoke = coursejiaoke;
	}

	public String getSearch() {
		return search;
	}

	public void setSearch(String search) {
		this.search = search;
	}

	public String[] getCheckbox() {
		return checkbox;
	}

	public void setCheckbox(String[] checkbox) {
		this.checkbox = checkbox;
	}

	
	public List<PptAndContent> getPac() {
		return pac;
	}

	public void setPac(List<PptAndContent> pac) {
		this.pac = pac;
	}

	public String getStartdate() {
		return startdate;
	}

	public void setStartdate(String startdate) {
		this.startdate = startdate;
	}

	public String getEnddate() {
		return enddate;
	}

	public void setEnddate(String enddate) {
		this.enddate = enddate;
	}

	public int getCurrentpage() {
		return currentpage;
	}

	public void setCurrentpage(int currentpage) {
		this.currentpage = currentpage;
	}

	public int getPagesize() {
		return pagesize;
	}

	public void setPagesize(int pagesize) {
		this.pagesize = pagesize;
	}

	public String getPptid() {
		return pptid;
	}

	public void setPptid(String pptid) {
		this.pptid = pptid;
	}

	public void setInputStream(InputStream inputStream) {
		this.inputStream = inputStream;
	}

	public InputStream getInputStream() {
		return inputStream;
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public String[] getDownloadcheck() {
		return downloadcheck;
	}

	public void setDownloadcheck(String[] downloadcheck) {
		this.downloadcheck = downloadcheck;
	}

	public String[] getDownLoadPaths() {
		return downLoadPaths;
	}

	public void setDownLoadPaths(String[] downLoadPaths) {
		this.downLoadPaths = downLoadPaths;
	}


	public String[] getDownLoadNames() {
		return downLoadNames;
	}

	public void setDownLoadNames(String[] downLoadNames) {
		this.downLoadNames = downLoadNames;
	}

	public static String getLocalpath() {
		return localpath;
	}

	public static void setLocalpath(String localpath) {
		PptAction.localpath = localpath;
	}

	public OutputStream getRes() {
		return res;
	}

	public void setRes(OutputStream res) {
		this.res = res;
	}

	public ZipOutputStream getZos() {
		return zos;
	}

	public void setZos(ZipOutputStream zos) {
		this.zos = zos;
	}

	public String getOutPath() {
		return outPath;
	}

	public void setOutPath(String outPath) {
		this.outPath = outPath;
	}

	public List<PptTeaContent> getPtc() {
		return ptc;
	}

	public void setPtc(List<PptTeaContent> ptc) {
		this.ptc = ptc;
	}

	public String[] getDelcheck() {
		return delcheck;
	}

	public void setDelcheck(String[] delcheck) {
		this.delcheck = delcheck;
	}

	
	
}
